import { createRouter, createWebHashHistory } from 'vue-router';
import { storage } from '@/utils/storage-util';
import { firstMenu } from '@/utils/map-menus';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'root',
      redirect: '/main'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/login-page.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/main-page.vue')
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('@/views/not-found/not-found.vue')
    }
  ]
});

router.beforeEach((to) => {
  const token = storage.get('token');
  if (to.path !== '/login' && !token) {
    return '/login';
  }
  if (to.path === '/login' && token) {
    return '/main';
  }
  if (to.path === '/main' && token) {
    return firstMenu?.url;
  }
});

export default router;
